package VariantEval;
use lib "$ENV{MYSQL_DRAW}/lib";
use MyTools;
use strict;
use vars qw($VERSION @ISA @EXPORT @EXPORT_OK);
require Exporter;
 
@ISA = qw(Exporter AutoLoader);

@EXPORT = qw( readVariantEval );

use Data::Dumper;

sub readVariantEval {
	my ($dbh, $path_prefix, $suffix, $modifier, $field_list) = @_;
	my %hash;
	my %RV = ();
	foreach my $ana_name (keys %{$field_list}) {
		read_analysis($dbh, "$path_prefix.$suffix", $ana_name, \%RV, $modifier, $field_list->{$ana_name});	
	}
# 	read_analysis($dbh, $fh, 'Analysis Description:  	Ti\/Tv Variant Evaluator', \%RV, $modifier, $field_list);
# 	read_analysis($dbh, $fh, "Analysis Description:  	the overlap between eval and comp sites", \%RV, $modifier, $field_list);
	return \%RV;
}

sub read_analysis {
	my ($dbh, $file, $ana_name, $RV, $modifier, $field_list) = @_;
	open(my $fh, $file) || die "cannot open $file\n";
	while (<$fh>) {
##:GATKReport.v1.0:8
		last if /^#.+$ana_name/;
	}
#CompOverlap  CompRod  EvalRod  JexlExpression  Novelty  nEvalVariants  nCompVariants  novelSites  nVariantsAtComp  compRate           nConcordant  concordantRate   
	my $header_line = <$fh>;
	chomp($header_line);
	my @headers = split(/\s{2,}/, $header_line);
	my $value_line = <$fh>; ## only parse "all"
	chomp($value_line);
	my @values = split(/\s{2,}/, $value_line);
	foreach my $fd (@{$field_list}) {
		my $metric_id = MyTools::fetchrow1col1_arrayref($dbh, "select MIID from MetricInfo where ", {'FieldName' => $fd, 'Modifier' => $modifier}) or die "Field $fd $modifier not found\n";
#		printf STDERR "$ana_name\t$fd\t$metric_id\n";
		my $fd_val = "NA";
		for (my $i=0; $i < scalar @headers; $i++) {
			if ($headers[$i] eq $fd) {
				$fd_val = $values[$i];
				last;
			}
		}
		$RV->{$metric_id}->{'value'} = $fd_val;
		$RV->{$metric_id}->{'field_name'} = $fd;
	}
	close $fh;
}

1;

